//
//  Ethereum.swift
//  Monujo
//
//  Created by user on 2024/1/2.
//

import Foundation
import CryptoSwift


class EthereumChain : Chain {
    override func is_valid_address(address: String) -> Bool {
        true
    }
    
    func eip55ChecksumAddress(_ address: String) -> String {
        let address = address.lowercased().withoutHexPrefix()
        let addressBytes = address.bytes
        let hash = SHA3(variant: .keccak256).calculate(for: addressBytes)
        var checksumAddress = "0x"
        for (index, char) in address.enumerated() {
            let hashByte = hash[index / 2]
            if "0123456789abcdef".contains(char) {
                let charValue: UInt8
                if index % 2 == 0 {
                    charValue = (hashByte >> 4) & 0xf
                } else {
                    charValue = hashByte & 0xf
                }

                checksumAddress.append(charValue > 7 ? char.uppercased() : String(char))
            } else {
                checksumAddress.append(char)
            }
        }

        return checksumAddress
    }
    
    func isValidEthereumAddress(_ address: String) -> Bool {
        let real_address = address.withoutCustomPrefix()
        // 1. 长度检查
        guard real_address.count == 42 else {
            return false
        }

        // 2. 正则表达式验证
        let regex = try! NSRegularExpression(pattern: "^0x[a-fA-F0-9]{40}$")
        let range = NSRange(location: 0, length: real_address.utf16.count)
        guard regex.firstMatch(in: real_address, options: [], range: range) != nil else {
            return false
        }

        // 3. EIP-55 校验（可选）
        return true
    }
}

private extension String {
    func withoutHexPrefix() -> String {
        return hasPrefix("0x") ? String(dropFirst(2)) : self
    }
    
    func withoutCustomPrefix() -> String {
        return hasPrefix("Ethereum:") ? String(dropFirst(9)) : self
    }
}
